<template>
  <van-popup v-model:show="showPicker" round position="bottom" class="user-data-container">
    <!-- 导航 -->
    <view class="card">
      <view class="nav-container">
        <span
          class="nav-name"
          v-for="(navItem, index) in navData"
          :key="index"
          @click="pop(navItem, index)"
        >
          <span class="interval" v-if="index !== 0">|</span>
          <i v-if="navItem.icon" :class="navItem.icon" style="padding: 0 8rpx" />
          <span v-else style="padding: 0 8rpx">{{ navItem.name }}</span>
        </span>
      </view>
    </view>
    <!-- 部门 -->
    <view class="card">
      <van-cell
        :title="deptItem.name"
        size="large"
        v-for="(deptItem, index) in deptData"
        :key="index"
      >
        <template #right-icon>
          <view class="cell-icon" @click="nextGrade(deptItem)">
            <van-icon name="list-switch" class="suffix-icon" />
            <span class="suffix-text">下级</span>
          </view>
        </template>
      </van-cell>
    </view>

    <!-- 人员 -->
    <view class="card">
      <van-checkbox-group v-model="_id_value">
        <van-cell
          :title="userItem.name"
          size="large"
          clickable
          v-for="(userItem, index) in userData"
          :key="index"
          @click="clickItem(userItem, index)"
        >
          <template #right-icon>
            <van-checkbox
              :name="userItem.id"
              :ref="(el) => (checkboxRefs[index] = el)"
              @click.stop="clickItem(userItem, index)"
            />
          </template>
        </van-cell>
      </van-checkbox-group>
      <van-empty description="暂无人员" v-if="userData.length < 1" />
    </view>

    <aster-tabbar
      ref="userTabbarRef"
      :customStyle="{
        borderTopLeftRadius: '10px',
        borderTopRightRadius: '10px',
      }"
    >
      <van-button type="primary" block @click="onConfirm">确定选择</van-button>
    </aster-tabbar>
  </van-popup>
</template>
<script setup lang="ts">
  import {
    selectUsersByDeptIdsApi,
    selectUsersByRoleIdsApi,
    userAllApi,
    userDeptInfoApi,
  } from '@/api/sys/user';
  import { memberByRoleIdsApi } from '@/api/workflow/auth';
  import { isNotEmpty } from '@/utils/is';
  import { computed, onBeforeMount, PropType, ref } from 'vue';

  const emits = defineEmits(['confirm']);
  const props = defineProps({
    canselected: {
      type: Object as PropType<{ type: string; ids: string[] }>,
      default: () => ({
        type: 'user',
        ids: [],
      }),
    },
    multiple: {
      type: Boolean,
      default: false,
    },
  });

  const checkboxRefs = ref<any[]>([]);
  // 显示弹出层
  const showPicker = ref(false);
  // 所有用户信息
  const userList = ref<User.UserInfo[]>([]);
  // 导航数据
  const navData = ref<User.UserDeptModel[]>([]);
  // 用户数据
  const userData = ref<User.UserDeptModel[]>([]);
  // 部门数据
  const deptData = ref<User.UserDeptModel[]>([]);
  // 是否多选, 默认单选
  const multiple = ref<boolean>(false);
  // value
  const _value = ref<User.UserDeptModel[]>([]);
  // checkbox value
  const _id_value = ref<string[]>([]);
  // 限制使用的用户ID
  const limitUserIds = ref<string[]>([]);

  /**
   * @description: 点击导航
   * @param deptItem 部门对象
   * @param index 导航索引
   */
  const pop = (dept: User.UserDeptModel, index: number) => {
    navData.value = navData.value.slice(0, index + 1);
    getUserDeptData(dept.id);
  };

  /**
   * @description: 下一级
   * @param deptItem 部门对象
   */
  const nextGrade = (dept: User.UserDeptModel) => {
    navData.value.push(dept);
    getUserDeptData(dept.id);
  };

  /**
   * @description: 根据部门id批量查询用户信息
   * @param {*} ids 部门id集合
   * @return {*}
   */
  const getUsersByDeptIdsApi = async (ids: string[]) => {
    await selectUsersByDeptIdsApi(ids).then(({ data }) => {
      // limitUserIds.value 不存在id，则添加
      data.forEach((item: User.UserInfo) => {
        if (!limitUserIds.value.includes(item.id)) {
          limitUserIds.value.push(item.id);
        }
      });
    });
  };

  /**
   * @description: 根据系统角色id批量查询用户信息
   * @param {*} ids 角色id集合
   * @return {*}
   */
  const getUsersByRoleIdsApi = async (ids: string[]) => {
    await selectUsersByRoleIdsApi(ids).then(({ data }) => {
      // limitUserIds.value 不存在id，则添加
      data.forEach((item: Role.RoleUserInfo) => {
        if (!limitUserIds.value.includes(item.userId)) {
          limitUserIds.value.push(item.userId);
        }
      });
    });
  };

  /**
   * @description: 获取流程角色ID查询用户信息
   * @param {*} ids 角色id集合
   * @return {*}
   */
  const getUsersByFlowRoleApi = async (ids: string[]) => {
    await memberByRoleIdsApi(ids).then(({ data }) => {
      // limitUserIds.value 不存在id，则添加
      data.forEach((item: WorkAuth.MemberInfo) => {
        if (item.memberId && !limitUserIds.value.includes(item.memberId)) {
          limitUserIds.value.push(item.memberId);
        }
      });
    });
  };

  /**
   * @description: 获取用户部门数据
   */
  const getUserDeptData = async (deptId: string) => {
    userData.value = [];
    deptData.value = [];
    limitUserIds.value = [];
    // 限制类型, 用户ID | 部门ID | 系统角色ID | 流程角色ID
    const type = _canselected.value?.type;
    const ids = _canselected.value?.ids;
    // 判断ids是否有值，有则需要做权限筛选，获取需要过滤的用户id
    if (ids && isNotEmpty(ids)) {
      switch (type) {
        case 'user':
          limitUserIds.value = ids;
          break;
        case 'dept':
          // 通过部门id批量查询部门下的所有用户
          getUsersByDeptIdsApi(ids);
          break;
        case 'sysRole':
          // 通过角色id批量查询角色下的所有用户
          getUsersByRoleIdsApi(ids);
          break;
        case 'flowRole':
          getUsersByFlowRoleApi(ids);
          break;
        default:
          break;
      }
    }
    await userDeptInfoApi(deptId).then(({ data }) => {
      if (data && data.length > 0) {
        data.forEach((item) => {
          if (item.type == 'dept') {
            deptData.value.push(item);
          } else if (item.type == 'user') {
            userData.value.push(item);
            // 过滤userData，排除在limitUserIds数组中不存在的数据
            if (limitUserIds.value.length > 0) {
              userData.value = userData.value.filter((item: User.UserDeptModel) => {
                return limitUserIds.value.some((id: string) => {
                  return item.id === id;
                });
              });
            }
          }
        });
      }
    });
  };

  /**
   * @description: 点击人员
   * @param userItem 用户对象
   */
  const clickItem = (user: User.UserDeptModel, index: number) => {
    checkboxRefs.value[index].toggle();
    // 如果单选
    if (!multiple.value) {
      if (_id_value.value.length > 0) {
        _id_value.value = [user.id];
        _value.value = [user];
      } else {
        _value.value = [];
      }
    } else {
      // 如果存在
      if (_id_value.value.indexOf(user.id) !== -1) {
        _value.value.push(user);
      } else {
        for (let i = 0; i < _value.value.length; i++) {
          if (_value.value[i].id === user.id) {
            _value.value.splice(i, 1);
          }
        }
      }
    }
  };

  /**
   * @description: 确认选择
   */
  const onConfirm = () => {
    emits('confirm', _value.value);
    showPicker.value = false;
  };

  /**
   * @description: 限制选中人员
   */
  const _canselected = computed(() => {
    return props.canselected;
  });

  /**
   * @description: 获取所有用户信息
   */
  const getAllUserInfo = async () => {
    await userAllApi().then(({ data }) => {
      userList.value = data;
    });
  };

  // 初始化赋值
  const init = (defaultValue?: string[]) => {
    multiple.value = props.multiple;
    if (defaultValue && isNotEmpty(defaultValue) && isNotEmpty(userList.value)) {
      _id_value.value = defaultValue;
      _value.value = userList.value
        .filter((f) => {
          return f.id && defaultValue.indexOf(f.id) !== -1;
        })
        .map((m) => {
          const name = m.realName ? m.realName : m.nickName;
          return { id: m.id ? m.id : '', name: name ? name : '', type: 'user' };
        });
    }
    showPicker.value = true;
  };

  onBeforeMount(async () => {
    await getAllUserInfo();
    navData.value.push({ id: '0', name: '全部', type: 'dept', icon: 'iconfont icon-SmartHome' });
    await getUserDeptData('0');
  });

  defineExpose({
    init,
  });
</script>
<style scoped lang="scss">
  .user-data-container {
    background-color: #f8f8f8;
    height: 60%;
  }
  .card {
    width: 100%;
    margin-top: 20rpx;
  }

  .cell-icon {
    height: 100%;
    line-height: 1;
  }

  .suffix-icon {
    color: #1989fa;
    scale: (1.1);
  }

  .suffix-text {
    color: #1989fa;
  }

  .nav-container {
    height: 35px;
    padding-left: 10px;
    font-size: 16px;
    display: flex;
    align-items: center;
  }

  .interval {
    padding: 0px 3px;
    color: #959292;
  }

  .nav-name {
    color: #1989fa;
  }
  .field-right {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
  }
</style>
